package com.binarycube.webserver.datasource;

import java.util.HashMap;
import java.util.Map;

import com.binarycube.webserver.ClazzLoader;
import com.binarycube.webserver.config.DataManagerConfig;
import com.binarycube.webserver.config.DatasourceConfig;

public class DataManager {

	private DataManagerConfig _config;
	private static DataManager _instance;
	
	Map<String, IDataSource> _cache;
	
	public static void init(DataManagerConfig cfg) {
		if (_instance == null) _instance = new DataManager(cfg);
	}
	
	public static DataManager getInstance(){
		return _instance;
	}
	
	
	private DataManager(DataManagerConfig cfg){
		_cache = new HashMap<String, IDataSource>();
		_config = cfg;
	}

	public IDataSource getDataSource(String name){
		IDataSource ds = _cache.get(name);
		if (ds == null) {
			DatasourceConfig dsc = _config.getDatasource(name);
			if (dsc != null) {
				ds = (IDataSource)ClazzLoader.getInstanceOf(dsc.getClazz());
				if (ds != null) ds.configure(dsc);
			}
		} 
		return ds;
	}
	
	public void clearCache(){
		_cache = new HashMap<String, IDataSource>();
	}
	
	
}
